import { Contact, Record, Category } from '../types';
import StorageManager from './storage';

class ExcelManager {
  // 导出数据到Excel
  static async exportToExcel(): Promise<void> {
    try {
      const data = await StorageManager.getAllData();
      
      // 创建工作簿
      const workbook = {
        Sheets: {
          // 联系人表
          '联系人': this.createContactsSheet(data.contacts),
          // 收礼记录表
          '收礼记录': this.createRecordsSheet(data.records.filter(r => r.type === 'receive')),
          // 送礼记录表
          '送礼记录': this.createRecordsSheet(data.records.filter(r => r.type === 'give')),
          // 其他往来表
          '其他往来': this.createRecordsSheet(data.records.filter(r => r.type === 'other'))
        },
        SheetNames: ['联系人', '收礼记录', '送礼记录', '其他往来']
      };

      // 转换为Excel文件
      const excelBuffer = this.workbookToBuffer(workbook);
      
      // 保存文件
      const filePath = `${wx.env.USER_DATA_PATH}/favorflow_backup_${new Date().getTime()}.xlsx`;
      await this.saveFile(filePath, excelBuffer);
      
      // 下载文件
      await this.downloadFile(filePath);
    } catch (error) {
      console.error('导出Excel失败:', error);
      throw error;
    }
  }

  // 从Excel导入数据
  static async importFromExcel(filePath: string): Promise<void> {
    try {
      // 读取Excel文件
      const workbook = await this.readExcelFile(filePath);
      
      // 解析数据
      const contacts = this.parseContactsSheet(workbook.Sheets['联系人']);
      const records = [
        ...this.parseRecordsSheet(workbook.Sheets['收礼记录'], 'receive'),
        ...this.parseRecordsSheet(workbook.Sheets['送礼记录'], 'give'),
        ...this.parseRecordsSheet(workbook.Sheets['其他往来'], 'other')
      ];
      
      // 保存数据
      await StorageManager.saveAllData({
        contacts,
        records,
        categories: [], // 需要重新创建分类
        settings: await StorageManager.getSettings()
      });
    } catch (error) {
      console.error('导入Excel失败:', error);
      throw error;
    }
  }

  // 创建联系人表
  private static createContactsSheet(contacts: Contact[]): any {
    const headers = ['姓名', '分类', '电话', '生日', '备注', '创建时间', '更新时间'];
    const rows = contacts.map(contact => [
      contact.name,
      contact.category,
      contact.phone || '',
      contact.birthday || '',
      contact.notes || '',
      contact.createTime,
      contact.updateTime
    ]);
    
    return {
      '!ref': `A1:G${rows.length + 1}`,
      A1: { v: headers[0], t: 's' },
      B1: { v: headers[1], t: 's' },
      C1: { v: headers[2], t: 's' },
      D1: { v: headers[3], t: 's' },
      E1: { v: headers[4], t: 's' },
      F1: { v: headers[5], t: 's' },
      G1: { v: headers[6], t: 's' },
      ...rows.reduce((acc, row, index) => {
        const rowNum = index + 2;
        return {
          ...acc,
          [`A${rowNum}`]: { v: row[0], t: 's' },
          [`B${rowNum}`]: { v: row[1], t: 's' },
          [`C${rowNum}`]: { v: row[2], t: 's' },
          [`D${rowNum}`]: { v: row[3], t: 's' },
          [`E${rowNum}`]: { v: row[4], t: 's' },
          [`F${rowNum}`]: { v: row[5], t: 's' },
          [`G${rowNum}`]: { v: row[6], t: 's' }
        };
      }, {})
    };
  }

  // 创建记录表
  private static createRecordsSheet(records: Record[], type: 'receive' | 'give' | 'other'): any {
    const headers = ['联系人', '金额', '礼物类型', '日期', '场合', '备注', '创建时间', '更新时间'];
    const rows = records.map(record => [
      record.contactId,
      record.amount || '',
      record.giftType || '',
      record.date,
      record.occasion || '',
      record.notes || '',
      record.createTime,
      record.updateTime
    ]);
    
    return {
      '!ref': `A1:H${rows.length + 1}`,
      A1: { v: headers[0], t: 's' },
      B1: { v: headers[1], t: 's' },
      C1: { v: headers[2], t: 's' },
      D1: { v: headers[3], t: 's' },
      E1: { v: headers[4], t: 's' },
      F1: { v: headers[5], t: 's' },
      G1: { v: headers[6], t: 's' },
      H1: { v: headers[7], t: 's' },
      ...rows.reduce((acc, row, index) => {
        const rowNum = index + 2;
        return {
          ...acc,
          [`A${rowNum}`]: { v: row[0], t: 's' },
          [`B${rowNum}`]: { v: row[1], t: 'n' },
          [`C${rowNum}`]: { v: row[2], t: 's' },
          [`D${rowNum}`]: { v: row[3], t: 's' },
          [`E${rowNum}`]: { v: row[4], t: 's' },
          [`F${rowNum}`]: { v: row[5], t: 's' },
          [`G${rowNum}`]: { v: row[6], t: 's' },
          [`H${rowNum}`]: { v: row[7], t: 's' }
        };
      }, {})
    };
  }

  // 解析联系人表
  private static parseContactsSheet(sheet: any): Contact[] {
    const contacts: Contact[] = [];
    const range = sheet['!ref'].split(':');
    const startRow = parseInt(range[0].replace(/[A-Z]/g, ''));
    const endRow = parseInt(range[1].replace(/[A-Z]/g, ''));
    
    for (let row = startRow + 1; row <= endRow; row++) {
      contacts.push({
        id: `contact_${row}`,
        name: sheet[`A${row}`]?.v || '',
        category: sheet[`B${row}`]?.v || '',
        phone: sheet[`C${row}`]?.v || undefined,
        birthday: sheet[`D${row}`]?.v || undefined,
        notes: sheet[`E${row}`]?.v || undefined,
        createTime: sheet[`F${row}`]?.v || new Date().toISOString(),
        updateTime: sheet[`G${row}`]?.v || new Date().toISOString()
      });
    }
    
    return contacts;
  }

  // 解析记录表
  private static parseRecordsSheet(sheet: any, type: 'receive' | 'give' | 'other'): Record[] {
    const records: Record[] = [];
    const range = sheet['!ref'].split(':');
    const startRow = parseInt(range[0].replace(/[A-Z]/g, ''));
    const endRow = parseInt(range[1].replace(/[A-Z]/g, ''));
    
    for (let row = startRow + 1; row <= endRow; row++) {
      records.push({
        id: `record_${row}`,
        contactId: sheet[`A${row}`]?.v || '',
        type,
        amount: sheet[`B${row}`]?.v || undefined,
        giftType: sheet[`C${row}`]?.v || undefined,
        date: sheet[`D${row}`]?.v || new Date().toISOString(),
        occasion: sheet[`E${row}`]?.v || undefined,
        notes: sheet[`F${row}`]?.v || undefined,
        createTime: sheet[`G${row}`]?.v || new Date().toISOString(),
        updateTime: sheet[`H${row}`]?.v || new Date().toISOString()
      });
    }
    
    return records;
  }

  // 将工作簿转换为Buffer
  private static workbookToBuffer(workbook: any): ArrayBuffer {
    // 这里需要引入xlsx库来实现
    // 由于小程序限制，我们可以使用其他方式实现
    return new ArrayBuffer(0);
  }

  // 保存文件
  private static async saveFile(filePath: string, buffer: ArrayBuffer): Promise<void> {
    return new Promise((resolve, reject) => {
      const fs = wx.getFileSystemManager();
      fs.writeFile({
        filePath,
        data: buffer,
        encoding: 'binary',
        success: resolve,
        fail: reject
      });
    });
  }

  // 下载文件
  private static async downloadFile(filePath: string): Promise<void> {
    return new Promise((resolve, reject) => {
      wx.saveFile({
        tempFilePath: filePath,
        success: resolve,
        fail: reject
      });
    });
  }

  // 读取Excel文件
  private static async readExcelFile(filePath: string): Promise<any> {
    // 这里需要引入xlsx库来实现
    // 由于小程序限制，我们可以使用其他方式实现
    return {};
  }
}

export default ExcelManager; 